import { defineStore } from 'pinia'
import variables from '@/styles/style.module.scss'

export interface GlobalStatus {
  isDark: boolean
  sidebarOpened: boolean
  opNames: { [key: string]: boolean }
  requestNumber: number
  error: {
    status: boolean
    message?: string
  }
}

export const useGlobalStore = defineStore('global', {
  state: (): GlobalStatus => ({
    isDark: false,
    sidebarOpened: true,
    requestNumber: 0,
    opNames: {},
    error: {
      status: false
    }
  }),

  getters: {
    cssVar: () => variables,

    isLoading: state => {
      return state.requestNumber > 0
    },

    isOpLoading: state => (opName: string) => {
      return state.opNames[opName] || false
    }
  },

  actions: {
    triggerSidebarOpened() {
      this.sidebarOpened = !this.sidebarOpened
    },

    togglerDark(isDark: boolean) {
      this.isDark = isDark
    },

    startLoading(payload?: { opName: string }) {
      this.requestNumber++
      if (payload) {
        this.opNames[payload.opName] = true
      }
    },

    finishLoading(payload?: { opName: string }) {
      setTimeout(() => {
        this.requestNumber--
        if (payload) {
          delete this.opNames[payload.opName]
        }
      }, 500)

      // this.requestNumber--
      // if (payload) {
      //   delete this.opNames[payload.opName]
      // }
    },

    setError(error: { status: boolean; message?: string }) {
      this.error = error
    }
  }
})
